package com.lawyer.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.lawyer.entity.Documents;
import com.lawyer.entity.MoneyFlows;
import com.lawyer.entity.User;
import com.lawyer.entity.UserMicroInfo;
import com.lawyer.model.Message;
import com.lawyer.model.MessageConstant;
import com.lawyer.repository.DocumentsRepository;
import com.lawyer.repository.MoneyFlowsRepository;
import com.lawyer.repository.UserRepository;
import com.lawyer.uitls.DateUtils;

@RestController
@RequestMapping(value = "/consumeMsg")
@Api(tags = "消息")
@SuppressWarnings("all")
public class ConsumeMsgController {

	protected final Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private EntityManager entityManager;
	@Autowired
	private DocumentsRepository documentsRepository;

	@Autowired
	private UserRepository userRepository;

	@Autowired
	private MoneyFlowsRepository moneyFlowsRepository;

	@RequestMapping(value = "/myMaiInfo", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "用户电话咨询", notes = "用户电话咨询")
	@ApiImplicitParams({ @ApiImplicitParam(name = "page", dataType = "integer", paramType = "query", value = "第几页"),
			@ApiImplicitParam(name = "size", dataType = "integer", paramType = "query", value = "分页条数") })
	public HttpEntity<?> myMaiInfo(@PageableDefault(page = 0, sort = { "createdDate" }, direction = Sort.Direction.DESC) Pageable pageable, String startDate, String endDate,
			@RequestParam(required = true) String userId) {
		Message msg = new Message();
		try {

			if (StringUtils.isNotEmpty(userId)) {

				CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();

				CriteriaQuery<UserMicroInfo> criteriaQuery = criteriaBuilder.createQuery(UserMicroInfo.class);

				Root<UserMicroInfo> root = criteriaQuery.from(UserMicroInfo.class);
				//根据统计结果排序
				criteriaQuery.orderBy(criteriaBuilder.desc(root.get("createdDate")));

				// 查询条件

				List<Predicate> predicates = new ArrayList<>();

				predicates.add(criteriaBuilder.equal(root.get("userId"), userId));

				// 日期（范围）

				if (StringUtils.isNotEmpty(startDate)) {
					Date begin = DateUtils.getDayBeginOrEndTime(startDate, "begin");

					predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createdDate"), begin));
				}
				if (StringUtils.isNotEmpty(endDate)) {
					Date end = DateUtils.getDayBeginOrEndTime(endDate, "end");

					predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("createdDate"), end));
				}

				// 将所有条件用 and 联合起来
				if (!CollectionUtils.isEmpty(predicates)) {
					criteriaQuery.where(criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])));
				}

				// 记录当前sql查询结果总条数
				List<UserMicroInfo> counts = entityManager.createQuery(criteriaQuery).getResultList();
				// sql查询对象
				TypedQuery<UserMicroInfo> createQuery = entityManager.createQuery(criteriaQuery);
				// 设置分页参数
				createQuery.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
				createQuery.setMaxResults(pageable.getPageSize());

				Page page = new PageImpl<UserMicroInfo>(createQuery.getResultList(), pageable, counts.size());

				msg.setData(page);
			}

		} catch (Exception e) {
			e.printStackTrace();
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(MessageConstant.FAILED_MSG);
		}

		return new ResponseEntity<>(msg, HttpStatus.OK);

	}

	@RequestMapping(value = "/myDocuments", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "付费项目", notes = "付费项目")
	@ApiImplicitParams({ @ApiImplicitParam(name = "page", dataType = "integer", paramType = "query", value = "第几页"),
			@ApiImplicitParam(name = "size", dataType = "integer", paramType = "query", value = "分页条数") })
	public HttpEntity<?> myDocuments(@PageableDefault(page = 0, sort = { "createdDate" }, direction = Sort.Direction.DESC) Pageable pageable,
			@RequestParam(required = true) String userId) {

		Message msg = new Message();
		try {

			CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
			CriteriaQuery<Documents> criteriaQuery = criteriaBuilder.createQuery(Documents.class);
			Root<Documents> root = criteriaQuery.from(Documents.class);
			criteriaQuery.orderBy(criteriaBuilder.desc(root.get("createdDate")));
			// 查询条件
			List<Predicate> predicates = new ArrayList<>();

			if (StringUtils.isNotEmpty(userId)) {
				predicates.add(criteriaBuilder.equal(root.get("userId"), userId));

				// 日期（范围）

				// 将所有条件用 and 联合起来
				if (!CollectionUtils.isEmpty(predicates)) {
					criteriaQuery.where(criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])));
				}

				List<Documents> counts = entityManager.createQuery(criteriaQuery).getResultList();
				TypedQuery<Documents> createQuery = entityManager.createQuery(criteriaQuery);
				// 设置分页参数
				createQuery.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
				createQuery.setMaxResults(pageable.getPageSize());

				Page pageResult = new PageImpl<Documents>(createQuery.getResultList(), pageable, counts.size());

				msg.setData(pageResult);
				return new ResponseEntity<>(msg, HttpStatus.OK);

			}

			return new ResponseEntity<>(HttpStatus.NO_CONTENT);

		} catch (Exception e) {
			e.printStackTrace();
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(MessageConstant.FAILED_MSG);
		}
		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

	@ApiOperation(httpMethod = "PUT", value = "文书代写支付", notes = "documentId：文书代写id")
	@RequestMapping(value = "/pay", method = RequestMethod.PUT)
	public HttpEntity<?> pay(Long documentId, String userId) {
		Message msg = new Message();
		try {

			User user = userRepository.findOne(userId);

			if (user == null) {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("用户不存在");
				return new ResponseEntity<>(msg, HttpStatus.OK);
			}
			Documents document = documentsRepository.findOne(documentId);
			
			
			if (document == null) {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("没有找此文书");
				return new ResponseEntity<>(msg, HttpStatus.OK);
			}

			if (document.getPay()) {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("已支付,请勿重复支付");
				return new ResponseEntity<>(msg, HttpStatus.OK);
			}
			if (document.getOfferPrice() > user.getBalance()) {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("余额不足");
				return new ResponseEntity<>(msg, HttpStatus.OK);
			}

			user.setBalance(user.getBalance() - document.getOfferPrice());
			userRepository.save(user);
			document.setPay(true);
			documentsRepository.save(document);
			// 保存变更记录
			MoneyFlows flow = new MoneyFlows();
			flow.setTypeFlow(1);
			flow.setUserId(userId);
			flow.setUserName(user.getNickName());
			flow.setPhone(user.getPhone());
			flow.setUserType(user.getUserType());
			flow.setChangeMoney(0 - document.getOfferPrice());
			flow.setDescription(document.getDocumentsType());
			moneyFlowsRepository.save(flow);

		} catch (Exception e) {
			e.printStackTrace();
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(MessageConstant.FAILED_MSG);
		}

		return new ResponseEntity<>(msg, HttpStatus.OK);
	}
	
	@ApiOperation(httpMethod = "GET", value = "文书代详情", notes = "文书代详情")
	@RequestMapping(value = "/documentInfo", method = RequestMethod.GET)
	public HttpEntity<?> queryInfo(Long id) {
		Message msg = new Message();
		try {
			Documents doc = documentsRepository.findOne(id);
			msg.setData(doc);
		} catch (Exception e) {
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(MessageConstant.FAILED_MSG);
		}
		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

}
